package pl.sind.http.oauth;

import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;

import oauth.signpost.OAuthProvider;

public class OAuthProviderFactory {

	@SuppressWarnings("unchecked")
	public static OAuthProvider getProvider(Class<?> connectionType, String requestTokenUrl, String accessTokenUrl,
			String clientUrl) {
		try {
			Constructor<OAuthProvider> constructor = null;

			if (HttpURLConnection.class.isAssignableFrom(connectionType)) {
				constructor = (Constructor<OAuthProvider>) Class.forName(
						"oauth.signpost.basic.DefaultOAuthProvider")
						.getConstructor(
								new Class<?>[] { String.class, String.class, String.class });

			} else if (isApacheHttp(connectionType)) {
				constructor = (Constructor<OAuthProvider>) Class.forName(
						"oauth.signpost.commonshttp.CommonsHttpOAuthProvider")
						.getConstructor(
								new Class<?>[] { String.class, String.class, String.class });
			}

			if (constructor != null) {
				return constructor.newInstance(new Object[] { requestTokenUrl,
						accessTokenUrl, clientUrl });
			}

			return null;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static boolean isApacheHttp(Class<?> clazz) {
		String iface = "org.apache.http.HttpRequest";
		
		while(clazz!=null && !clazz.isInterface()){
			Class<?>[] interfaces = clazz.getInterfaces();
			if(hasInterface(interfaces, iface)){
				return true;
			}else{
				clazz = clazz.getSuperclass();
			}
		}
		
		return false;
	}
	
	
	private static boolean hasInterface(Class<?>[] ifaces, String iface){
		for (Class<?> i : ifaces) {
			if (i.getName().equals(iface)) {
				return true;
			}else if(hasInterface(i.getInterfaces(),iface)){
				return true;
			}
		}
		return false;
	}

}
